//
//  UITabBar+QSBadge.m
//  ZengLongSeSha
//
//  Created by apple on 2017/5/12.
//  Copyright © 2017年 Song. All rights reserved.
//

#import "UITabBar+QSBadge.h"

@implementation UITabBar (QSBadge)
/**
 *  显示数字badge
 */
- (void)showNumberBadgeOnItemAtItem:(NSInteger)index
{
    QSWindow
    UITabBarController *tabBarVC = (UITabBarController *)qs_Window.rootViewController;
    UITabBarItem *item = [tabBarVC.tabBar.items objectAtIndex:index];
    item.badgeColor = [UIColor redColor];
    NSString *badge = item.badgeValue;
    item.badgeValue = [NSString stringWithFormat:@"%ld", badge.integerValue + 1];
}

/**
 *  隐藏数字badge
 */
- (void)hideNumberBadgeOnItemAtItem:(NSInteger)index
{
    QSWindow
    UITabBarController *tabBarVC = (UITabBarController *)qs_Window.rootViewController;
    UITabBarItem *item = [tabBarVC.tabBar.items objectAtIndex:index];
    item.badgeValue = nil;
}

/**
 *  显示小红点
 */
- (void)showBadgeOnItemIndex:(NSInteger)index{
    
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 5;
    badgeView.backgroundColor = [UIColor redColor];
    CGRect tabFrame = self.frame;
    
    //确定小红点的位置
    QSWindow
    UITabBarController *tabBarVC = (UITabBarController *)qs_Window.rootViewController;
    float percentX = (index + 0.6) / tabBarVC.tabBar.items.count;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.1 * tabFrame.size.height);
    badgeView.frame = CGRectMake(x, y, 8, 8);
    [self addSubview:badgeView];
}

/**
 *  隐藏小红点
 */
- (void)hideBadgeOnItemIndex:(NSInteger)index{
    
    //移除小红点
    [self removeBadgeOnItemIndex:index];
    
}

- (void)removeBadgeOnItemIndex:(NSInteger)index{
    
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        
        if (subView.tag == 888+index) {
            
            [subView removeFromSuperview];
            
        }
    }
}
@end
